package com.cysyz.mylib.mailsender;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

public class SMTPMailSender {
	private Session session;
	private String host;
	private final String id;
	private final String password;
	
	public SMTPMailSender(String host_, String id_, String password_) {
		host = host_;
		id = id_;
		password = password_;
		init();
	}

	private void init() {
		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.host", this.host);
		props.setProperty("mail.debug", "true");
		props.setProperty("mail.smtp.auth", "true");
		session = Session.getInstance(props, new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(id, password);
			}
		});
	}
	
	/**
	 * 
	 * @param formatedAddress 显示名:<邮箱地址>
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	private String getEndcodedAddress(String formatedAddress) {
		String[] addressPart = formatedAddress.split(":");
		String encodedAddress = null;
		try {
			  encodedAddress = new StringBuilder(MimeUtility.encodeText(addressPart[0], "UTF-8", "B")).append(addressPart[1]).toString();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return encodedAddress;
	}
	
	public Mail generateAMail(String from, String to, String[] ccs, String[] bccs, String subject, String htmlConent) throws MessagingException {
		Message msg = new MimeMessage(session);
		msg.setSubject(subject);
		msg.setFrom(new InternetAddress(getEndcodedAddress(from)));
		msg.addRecipient(RecipientType.TO, new InternetAddress(to));
		if (ccs != null) {
			for (String cc : ccs) {
				msg.addRecipient(RecipientType.CC, new InternetAddress(getEndcodedAddress(cc)));
			}
		}
		if (bccs != null) {
			for (String bcc : bccs) {
				msg.addRecipient(RecipientType.BCC, new InternetAddress(getEndcodedAddress(bcc)));
			}
		}
		return new Mail(msg, htmlConent);
	}
	
	public Mail generateAMail(String from, String to, String[] ccs, String subject, String htmlConent) throws MessagingException {
		return this.generateAMail(from, to, ccs, null, subject, htmlConent);
	}
	public Mail generateAMail(String from, String to, String subject, String htmlConent) throws MessagingException {
		return this.generateAMail(from, to, null, null, subject, htmlConent);
	}
}
